import * as echarts from 'echarts';
import { isNil } from "lodash-es";
import React from "react";
import geoData from '../../assets/china-geo.json';
import { IProvinceGDP } from "../../core/interface";
import './index.scss';

export interface IProps {
  year: number;
  yearData: IProvinceGDP[];
  changeCurrentProvince: (v: string) => void;
  currentProvince: string;
  seriesData?: {
    name: string;
    value: number;
    data: IProvinceGDP;
  }[];
  title?: string;
  style?: React.CSSProperties;
}

/** 地图组件 */
const CountryMap: React.FC<IProps> = (props) => {
  const { yearData, year, changeCurrentProvince, currentProvince, seriesData, title, style } = props;
  const containerRef = React.useRef<HTMLDivElement>(null);
  const chartRef = React.useRef<echarts.ECharts>(null);

  const updateProvince = (v: string) => {
    if (v === currentProvince) changeCurrentProvince('');
    changeCurrentProvince(v);
  };

  const renderMap = () => {
    if (isNil(containerRef.current)) return;
    const { width, height } = containerRef.current.getBoundingClientRect();
    const chartWidth = width;
    const projection = d3.geo.mercator()
      .center([105, 36])
      .scale(850)
      .translate([chartWidth / 2, height / 2]);;
    echarts.registerMap('China', geoData);
    const option = {
      animation: true,
        title: {
          text: title ?? '各省GDP分布图',
          subtext: '为0代表数据缺失，可切换年份查看',
        },
      tooltip: {
        trigger: 'item',
        showDelay: 0,
        transitionDuration: 0.2,
        showContent: true,
        formatter: (params: {
          data: {
            name: string;
            value: number;
            data: IProvinceGDP;
          }
        }) => {
          const { name, value, data } = params.data ?? {};
          return `<div className="map-tooltip-container">
            <div>${year}年${name}GDP统计</div>
            <div>总GDP：${value}</div>
            <div>总人口：${data.population || '数据缺失'}</div>
            <div>第一产业：${data.gdp1 || '数据缺失'}</div>
            <div>第二产业：${data.gdp2 || '数据缺失'}</div>
            <div>第三产业：${data.gdp3 || '数据缺失'}</div>
            <div>就业人口：${data.employedPersonNumber || '数据缺失'}</div>
            <div>医保参保人口：${data.healthInstitutions || '数据缺失'}</div>
            <div> 出生率：${!!data.birthRate ? `${data.birthRate}%` : '数据缺失'}</div >
            <div> 死亡率：${!!data.deathRate ? `${data.deathRate}%` : '数据缺失'}</div > 
            <div> 自然增长率：${!!data.naturalGrowthRate ? `${data.naturalGrowthRate}%` : '数据缺失'}</div > 
          </div>`
        },
      },
      visualMap: {
        left: 'right',
        min: 0,
        max: !isNil(seriesData) ? Math.max(...seriesData.map(item => item.value)) : 70000,
        inRange: {
          color: [
            '#313695',
            '#4575b4',
            '#74add1',
            '#abd9e9',
            '#e0f3f8',
            '#ffffbf',
            '#fee090',
            '#fdae61',
            '#f46d43',
            '#d73027',
            '#a50026'
          ]
        },
        text: ['High', 'Low'], // 文本，默认为数值文本
        calculable: true
      },
      series: [
        {
          name: '中国各省份GDP',
          type: 'map',
          map: 'China',
          projection: {
            project: function (point) {
              return projection(point);
            },
            unproject: function (point) {
              return projection.invert(point);
            }
          },
          emphasis: {
            label: {
              show: true
            }
          },
          data: seriesData ?? (yearData ?? []).map(item => ({
            name: item.province,
            value: item.gdp,
            data: item,
          })),
        }
      ]
    };
    if (chartRef.current) {
      // update
      chartRef.current.setOption(option);
    } else {
      const chart = echarts.init(containerRef.current, null, {
        height,
        width: chartWidth,
      });

      chart.setOption(option);
      chart.on('click', (params) => {
        updateProvince(params.name);
      });
      chartRef.current = chart;
    }


  };

  React.useEffect(() => {
    if (!yearData?.length) return;
    renderMap();
  }, [yearData]);

  return (
    <div className="map-contaienr" ref={containerRef} style={ !!style ? style :{
      width: '60%',
      height: '100%',
    }}>

    </div>
  );
};

export default CountryMap;